package com.beka.frame.base;

import org.apache.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.context.support.ServletContextResourcePatternResolver;

import javax.servlet.ServletContext;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-4-17
 * Time: 下午11:53
 * 资源搜索器.
 */
public class ServletResourcePatternResovlerAndLoader extends DefaultResourceLoader implements ResourcePatternResolver {

    private static ServletResourcePatternResovlerAndLoader instance;
    private static Logger logger = Logger.getLogger(ServletResourcePatternResovlerAndLoader.class);

    public static void init(ServletContext servletContext) {
        instance = new ServletResourcePatternResovlerAndLoader(servletContext);
        logger.info("Servlet资源搜索器初始化成功.");
    }

    public static Resource[] getResourceArray(String locationPattern) throws IOException {
        if (instance == null || instance.servletContext == null)
            throw new RuntimeException("Servlet资源搜索器没有被正确的初始化, 请检查web.xml中的listener配置");
        return instance.getResources(locationPattern);
    }

    private ServletContext servletContext;
    private ResourcePatternResolver resourcePatternResolver = new ServletContextResourcePatternResolver(this);

    private ServletResourcePatternResovlerAndLoader(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public Resource[] getResources(String locationPattern) throws IOException {
        return this.resourcePatternResolver.getResources(locationPattern);
    }

    protected Resource getResourceByPath(String path) {
        return new ServletContextResource(this.servletContext, path);
    }
}
